package org.jianfa.homework.code.service.impl;

import org.apache.commons.lang.time.DateUtils;
import org.jianfa.homework.code.mapper.JianfaAuthCodeMapper;
import org.jianfa.homework.code.model.JianfaAuthCode;
import org.jianfa.homework.code.service.InternalCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Random;

@Service
public class InternalCodeServiceImpl implements InternalCodeService {

    private final static String NUMBERS = "0123456789";

    @Autowired
    private JianfaAuthCodeMapper jianfaAuthCodeMapper;

    /**
     * 随机生成6位数字的验证码
     *
     * @return
     */
    public String generateRandomCode() {
        Random random = new Random();

        StringBuffer stringBuffer = new StringBuffer();
        for (int i=0; i<6; i++) {
            stringBuffer.append(NUMBERS.charAt(random.nextInt(NUMBERS.length())));
        }
        return stringBuffer.toString();
    }

    /**
     * 保存验证码
     *
     * @param email
     * @param code
     * @return
     */
    public boolean saveCode(String email, String code) {
        Date createTime = new Date();
        Date expiretime = DateUtils.addMinutes(createTime, 10);

        JianfaAuthCode jianfaAuthCode = new JianfaAuthCode();
        jianfaAuthCode.setEmail(email);
        jianfaAuthCode.setCode(code);
        jianfaAuthCode.setCreatetime(createTime);
        jianfaAuthCode.setExpiretime(expiretime);
        int insert = jianfaAuthCodeMapper.insert(jianfaAuthCode);
        return insert > 0 ? true : false;
    }

    /**
     * 验证验证码
     *
     * @param email
     * @param code
     * @return
     */
    public Integer validate(String email, String code) {

        JianfaAuthCode jianfaAuthCode = jianfaAuthCodeMapper.selectByEmail(email);
        if (jianfaAuthCode == null) {
            return 1; //错误
        }
        Date now = new Date();
        Date date = jianfaAuthCode.getExpiretime();
        if (now.after(date)) {
            return 2; //超时
        }

        String realCode = jianfaAuthCode.getCode();
        if (realCode.equals(code)) {
            return 0; //正确
        }

        return 1; //错误
    }
}
